<template>
	<view class="upnav">
		<uv-form labelPosition="left" labelWidth="100" :model="updata" :rules="rules" ref="form">
			<!-- 姓名 -->
			<uv-form-item label="姓名" prop="name" borderBottom>
				<uv-input v-model="updata.name" border="none" />
			</uv-form-item>

			<!-- 开始时间 -->
			<uv-form-item label="开始时间" prop="star_time" borderBottom>
				<view class="selected-time" v-if="!isselstate" @click.stop="open('start')">
					{{ updata.star_time || '未选择时间' }}
				</view>
				<uv-datetime-picker 
					v-else 
					ref="datetimePickerStart" 
					v-model="updata.star_timeTimestamp"
					mode="datetime"
					@confirm="($event) => confirm('start', $event)"
					@cancel="() => { isselstate = false }">
				</uv-datetime-picker>
			</uv-form-item>

			<!-- 结束时间 -->
			<uv-form-item label="结束时间" prop="end_time" borderBottom>
				<view class="selected-time" v-if="!isselstateEnd" @click.stop="open('end')">
					{{ updata.end_time || '未选择时间' }}
				</view>
				<uv-datetime-picker 
					v-else 
					ref="datetimePickerEnd" 
					v-model="updata.end_timeTimestamp"
					mode="datetime"
					@confirm="($event) => confirm('end', $event)"
					@cancel="() => { isselstateEnd = false }">
				</uv-datetime-picker>
			</uv-form-item>

			<!-- 请假天数 -->
			<uv-form-item label="请假天数" prop="days" borderBottom>
				<uv-input type="digit" v-model.number="updata.days" border="none" disabled />
			</uv-form-item>

			

			<!-- 申请时间（只读） -->
			<uv-form-item label="申请时间" borderBottom>
				<view class="uni-form-item__box">{{ updata.apply_time }}</view>
			</uv-form-item>

			<!-- 申请人（只读） -->
			<uv-form-item label="申请人" borderBottom>
				<view class="uni-form-item__box">{{ updata.applicant }}</view>
			</uv-form-item>

			<!-- 部门（只读） -->
			<uv-form-item label="部门" borderBottom>
				<view class="uni-form-item__box">{{ updata.department }}</view>
			</uv-form-item>

			<!-- 请假原因 -->
			<uv-form-item label="请假原因" prop="reason"  borderBottom>
					<uv-textarea v-model="updata.reason" placeholder="请输入内容"></uv-textarea>
				
			</uv-form-item>
			
			<!-- 提交按钮 -->
			<uv-button type="primary" text="保存修改" customStyle="margin-top: 20px" @click="submit"></uv-button>
		</uv-form>
	</view>
</template>
<script>
export default {
	data() {
		return {
			updata: {
				name: '',
				star_time: '',          // 显示用的开始时间（字符串）
				end_time: '',            // 显示用的结束时间（字符串）
				days: 0,
				reason: '',
				leave_id: '',
				apply_time: '',
				applicant: '',
				department: '',
				star_timeTimestamp: null, // 中间变量保存时间戳
				end_timeTimestamp: null   // 中间变量保存时间戳
			},
			isselstate: false,
			isselstateEnd: false,
			rules: {
				name: [
					{ required: true, message: '请填写姓名', trigger: 'blur' }
				],
				star_time: [
					{ required: true, message: '请选择开始时间', trigger: 'change' }
				],
				end_time: [
					{ required: true, message: '请选择结束时间', trigger: 'change' }
				],
				days: [
					{ required: true, message: '请输入请假天数', trigger: 'blur' }
				],
				reason: [
					{ required: true, message: '请输入请假原因', trigger: 'blur' }
				]
			}
		};
	},
	onLoad(op) {
		if (op && op.data) {
			const data = JSON.parse(op.data);
			this.updata = {
				...data,
				star_time: data.star_time || '',
				end_time: data.end_time || '',
				star_timeTimestamp: data.star_time ? new Date(data.star_time).getTime() : null,
				end_timeTimestamp: data.end_time ? new Date(data.end_time).getTime() : null
			};
		}
		console.log('初始数据:', this.updata);
	},
	methods: {
		open(type) {
			if (type === 'start') {
				this.isselstate = true;
				this.$nextTick(() => {
					this.$refs.datetimePickerStart.open();
				});
			} else if (type === 'end') {
				this.isselstateEnd = true;
				this.$nextTick(() => {
					this.$refs.datetimePickerEnd.open();
				});
			}
		},
		confirm(type, timestamp) {
			console.log(timestamp)
			if (!timestamp) return;

			const dateStr = this.formatTimestamp(timestamp.value);

			if (type === 'start') {
				this.updata.star_time = dateStr;
				this.updata.star_timeTimestamp = timestamp;
			} else if (type === 'end') {
				this.updata.end_time = dateStr;
				this.updata.end_timeTimestamp = timestamp;
			}

			this.isselstate = false;
			this.isselstateEnd = false;

			// 自动计算天数
			this.calculateDays();
		},
		// 将13位时间戳转换为'YYYY-MM-DD HH:mm'格式
		  formatTimestamp(timestamp) {
		    
				let datea = new Date(timestamp);
				// console.log( Date(timestamp))
				// 	console.log( datea.getDay())
				
			   const year = datea.getFullYear();
			   const month = ('0' + (datea.getMonth() + 1)).slice(-2); // 月份是从0开始的
			   const day = ('0' + datea.getDate()).slice(-2);
			   const hours = ('0' + datea.getHours()).slice(-2);
			   const minutes = ('0' + datea.getMinutes()).slice(-2);
			   const seconds = ('0' + datea.getSeconds()).slice(-2);
			   return `${year}-${month}-${day} ${hours}:${minutes}`;
	
		   },
		calculateDays() {
			const start = new Date(this.updata.star_time);
			const end = new Date(this.updata.end_time);
			
			console.log("开始时间:", this.updata.star_time, "解析:", start);
			console.log("结束时间:", this.updata.end_time, "解析:", end);
			
			if (isNaN(start.getTime()) || isNaN(end.getTime())) {
				this.updata.days = 0;
				return;
			}

			if (end < start) {
				uni.showToast({ title: '结束时间不能早于开始时间', icon: 'none' });
				this.updata.days = 0;
				return;
			}

			const diffInMs = end - start;
			const days = Math.ceil(diffInMs / (1000 * 60 * 60 * 24));
			this.updata.days = days + 1; // 包含当天
		},
		submit() {
			// console.log('提交数据:', this.updata);
			uni.showToast({ title: '修改成功', icon: 'success' });
			uni.setStorageSync("updata",this.updata)
			
			setTimeout(() => {
				uni.navigateBack(); // 返回上一页
			}, 1000);
			
		}
	}
};
</script>
<style scoped>
.upnav {
	padding: 50rpx;
}

.selected-time {
	color: #666;
	font-size: 14px;
	line-height: 40px;
}

.uni-form-item__box {
	color: #666;
	font-size: 14px;
	line-height: 40px;
}
.inpur{
	background-color: red;
	height: 20vh;
	
}
</style>